package com.lumlord.common.shiro.service;

import java.io.UnsupportedEncodingException;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.lumlord.model.auto.TsysUser;

public class JWTCredentialsMatcher implements CredentialsMatcher {
    private final Logger logger = LoggerFactory.getLogger(JWTCredentialsMatcher.class);

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String tokenStr = (String) token.getCredentials();
        Object stored = info.getCredentials();
        String salt = stored.toString();

        TsysUser user = (TsysUser) info.getPrincipals().getPrimaryPrincipal();
        try{
            Algorithm algorithm = Algorithm.HMAC256(salt);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username",user.getUsername())
                    .build();
            verifier.verify(tokenStr);
            return true;
        }catch (JWTVerificationException e){
            logger.error("Token Error:{}", e.getMessage());
        } catch (IllegalArgumentException e) {
			
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return false;
    }
}